package cn.com.jit;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class ReservedWordChecker {

    private static final String DICTIONARY_FILE = "D:\\JIT_workspaces\\workspace\\competition-java-xhb\\src\\main\\java\\cn\\com\\jit\\ReservedWord.txt";
    private static final ReservedWordChecker INSTANCE = new ReservedWordChecker();

    private final Map<String, List<String>> dictionaries = new HashMap<>();

    private ReservedWordChecker() {
        loadDictionaries();
    }

    public static ReservedWordChecker getInstance() {
        return INSTANCE;
    }

    private void loadDictionaries() {
        try (BufferedReader reader = new BufferedReader(new FileReader(DICTIONARY_FILE))) {
            String line;
            String currentDictionaryName = null;
            boolean readingDictionary = false;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("# ")) {
                    currentDictionaryName = line.substring(2); // 去掉前缀 "# "
                    readingDictionary = true;
                } else if (readingDictionary && !line.isEmpty()) {
                    List<String> dictionary = dictionaries.computeIfAbsent(currentDictionaryName, k -> new ArrayList<>());
                    dictionary.add(line);
                } else {
                    readingDictionary = false;
                }
            }
        } catch (IOException e) {
            System.err.println("Error loading dictionaries: " + e.getMessage());
        }
    }

//    public boolean checkStringsInDictionaries(List<String> strings) {
//        return strings.stream()
//                .anyMatch(str -> dictionaries.values().stream()
//                        .anyMatch(dict -> dict.contains(str)));
//    }
    public Map<String, String> checkStringsInDictionaries(List<String> strings) {
        Map<String, String> result = new HashMap<>();

        // 将所有词典中的字符串及其对应的词典组预先存储在一个哈希表中
        Map<String, String> dictionaryMap = new HashMap<>();
        for (Map.Entry<String, List<String>> entry : dictionaries.entrySet()) {
            for (String word : entry.getValue()) {
                dictionaryMap.put(word, entry.getKey());
            }
        }

        // 遍历字符串列表并查找匹配项
        for (String str : strings) {
            if (dictionaryMap.containsKey(str)) {
                result.put(str, dictionaryMap.get(str));
            }
        }

        return result;
    }


    public static void main(String[] args) {
        ReservedWordChecker checker = ReservedWordChecker.getInstance();
        List<String> stringsToCheck = new ArrayList<>(Arrays.asList("apple", "grape", "watermelon", "pear", "kiwi"));
        Map<String, String> checkerResult = checker.checkStringsInDictionaries(stringsToCheck);
        System.out.println(checkerResult);
    }
}
